package com.bawei.yuekao.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import androidx.annotation.Nullable;

public class DownloadService  extends IntentService {

    public DownloadService() {
        super("DownloadService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //获得值
        Bundle bundle = intent.getExtras();
        String url1 = bundle.getString("url");
        String name = bundle.getString("name");

        try {
            URL url = new URL(url1);
            HttpURLConnection  httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            InputStream inputStream = httpURLConnection.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/Music/" + name + ".mp3");
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //下载完成发送广播
        Intent intent1 = new Intent();
        intent1.setAction("com.music.download");
        sendBroadcast(intent1);



    }
}
